import React, { useState } from 'react';
import cn from 'classnames';
import i from '@/index.module.css';
import s from './style.module.css';
import { Table, Message, Dialog, Button, Confirm, Progress, Pagination,Loading } from '@knownsec/react-component';
import { backupList, backupActive, getSystemDisk, delbackupList, backupDown ,backupNew,backupRecover,backupProgress} from '~/API';
import moment from 'moment';
export default function list() {
  const [refe, setRefe] = useState(false);
  const [selTable, setSelTable] = useState([]);
  const [upVisible, setUpVisible] = useState('');
  const [tableData, setTableData] = useState({ data: [], total: 0 });
  const [downlog, setDownlog] = useState('');
  const [isFull, setIsFull] = useState(false);
  const [percent, setPercent] = useState(0);
  const [loading, setLoading] = useState(false)

  const [searchInfo, setSearchInfo] = useState({ page: 1, count: 10 });
  const getList = async (e) => {
    setLoading(true)
    setTableData({ data: [], total: 0 });
    setSelTable([])
    setRefe(!refe)
    const list = await backupList({...e,kind:"backup"});
    console.log('[ list ]-25', list)
    const data = list.data.results
    setTableData({ data, total: list.data.count });
    setLoading(false)
  };
  const onSearch = (e) => {
    console.log('[e]-31', e)
    setSearchInfo({ page: e.page, count: e.limit });
    let params =  { page: e.page, count: e.limit };
    getList(params);
  };
  const ddisk = async () => {
    const res = await getSystemDisk({ master: 1 });
    if (res.data?.threshold<=res.data?.out_memery?.data_usage) {
      setIsFull(true);
    }
  };
  React.useMemo(() => {
    getList();
    ddisk();
  }, []);
  const columns = [
    {
      title: '备份文件名',
      dataIndex: 'file_name',
    },
    {
      title: '文件大小',
      dataIndex: 'file_size',
      render: (e, row) => {
        const e_ = (e / 1024 / 1024).toFixed(2);
        return <span>{e_}MB</span>;
      },
    },
    {
      title: 'sha1对比',
      dataIndex: 'sha1',
    },
    {
      title: '来源',
      dataIndex: 'source',
      render:(e)=>{return e||'--'}
    },
    {
      title: '创建时间',
      dataIndex: 'started_at',
      render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '--'),
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      className: s.w_5,
      render: (e, row) => {
        const id = row.id;
        return (
          <div className={s.btnBox}>
            <div 
              className={s.operation}
              style={{color:downlog===row.id?"#ccc":'#0b6fd6'}}
              onClick={async () => {
                if(downlog){
                    return false;
                }
                setDownlog(id);
               const res= await backupDown({ id: id });
               console.log('[ res ]-90', res)
                setDownlog('');
              }}
            >
              {downlog===row.id?'下载中':'下载'}
            </div>
            <div
              className={s.operation}
              onClick={() => {
                showDialog('recovery', id);
              }}
            >
              还原
            </div>
            <div
              className={s.operation}
              onClick={() => {
                delList([id]);
              }}
            >
              删除
            </div>
          </div>
        );
      },
    },
  ];
  const changeVisible = () => {
    setUpVisible(false);
    setPercent(0);
  };
  const delList = (e) => {
    Confirm({
      pro: true,
      title: '提示',
      message: <div className="confirmbox">您确认要删除选择的备份文件？</div>,
      onconfirm: async () => {
        const params = {
          ids: e || selTable,
        };
        const res = await delbackupList(params);
        getList({ page: 1, count: 10 });
        if (res.status === 'success') {
          setSelTable([]);
          setRefe(!refe)
          Message.show({
            pro: true,
            showClose: false,
            type: 'success',
            message: '删除成功',
          });
        }
      },
      oncancel: () => {},
    });
  };
  const showDialog = async (type, id) => {
    const textObj = {
      recovery: '数据还原操作将停止后台扫描，不能进行其他操作，您确定要进行还原操作？',
      backup: '数据备份操作将停止后台扫描，不能进行其他操作，您确定要进行备份操作？',
    };
    const textObj2 = { recovery: '数据还原', backup: '数据备份' };
    setPercent(0);
    Confirm({
      pro: true,
      title: '提示',
      message: <div className="confirmbox">{textObj[type]}</div>,
      onconfirm: async () => {
        setUpVisible(textObj2[type]);
        let setIn = null;
        if (type === 'backup') {
         const res= await backupNew();
         console.log('[ res ]-174', res)          
        } else if (type === 'recovery') {
          const res= await backupRecover({id});
          console.log('[ res ]-174', res)  
        }
        setIn = setInterval(async () => {
            const pace = await backupProgress({kind:type});
            console.log('[ pace ]-201', pace)
            setPercent(pace.data?.progress);
            if (pace.data.status == 2) {
              clearInterval(setIn);
              setPercent(100);
              setUpVisible('');
              getList(searchInfo);
              Message.show({
                pro: true,
                showClose: false,
                type: 'success',
                message:pace.message,
              });
            }else if (pace.data.status == 3) {
                clearInterval(setIn);
                setPercent(100);
                setUpVisible('');
                getList(searchInfo);
                Message.show({
                  pro: true,
                  showClose: false,
                  type: 'error',
                  message:pace.message,
                });
              }
          }, 2000);
      },
      oncancel: () => {},
    });
  };
  return (
    <div className={s.wordMain}>
      <p className={s.wordMain_h} style={{ display: isFull ? 'block' : 'none' }}>
        当前磁盘所需空间不足，无法进行数据备份，数据还原、数据还原、数据上传操作
      </p>
      <div className={s.tool}>
        <Button
          type="primary"
          pro
          disabled={selTable.length}
          onClick={() => {
            showDialog('backup');
          }}
        >
          数据备份
        </Button>
      </div>
      <div>
        <Button
          pro
          type="text"
          className="delete-btn p0"
          disabled={!selTable.length}
          onClick={() => {
            delList();
          }}
        >
          批量删除
        </Button>
      </div>
      {/* <Loading show={loading} /> */}
      <Table
        refre={refe}
        columns={columns}
        selectable
        className={s.table}
        tableLoading={loading}
        loadingLabel=""
        data={tableData.data}
        getCheckedList={(e) => {
          setSelTable(e);
        }}
      ></Table>
      {tableData.total > 10 && <Pagination
        key={Number(123)}
        className={s.pagination}
        current={searchInfo.page}
        showQuickJumper={{ goButton: true }}
        showSizeChanger={true}
        showTotal={(total) => `共${total}条`}
        pageSize={searchInfo.count}
        pageSizeOptions={['10', '20', '50']}
        total={tableData.total}
        onChange={(page, limit) => {
          onSearch({ page, limit });
        }}
      />}
      <Dialog
        className={cn(i.w400)}
        title={upVisible}
        visible={upVisible}
        closable={false}
        cancelText=""
        confirmText=""
        onhide={() => {
        //   changeVisible();
        }}
      >
        <div className={i.p20}>
          <p className={cn(i.tac)}>正在进行{upVisible}</p>
          <p className={cn(i.tac)}>进度:{percent}%</p>
          <Progress percent={percent + '%'} className={i.mt10} />
        </div>
      </Dialog>
    </div>
  );
}
